import pytest
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from pathlib import Path
from src.utils.reporting import TestReporter

# 路径配置
PROJECT_ROOT = Path(__file__).parent.parent
ARTIFACTS_DIR = PROJECT_ROOT / "artifacts"
SCREENSHOTS_DIR = ARTIFACTS_DIR / "screenshots"
REPORTS_DIR = ARTIFACTS_DIR / "reports"

@pytest.fixture(scope="session")
def reporter():
    """覆盖默认报告生成器"""
    # 确保目录存在
    ARTIFACTS_DIR.mkdir(parents=True, exist_ok=True)
    SCREENSHOTS_DIR.mkdir(parents=True, exist_ok=True)
    REPORTS_DIR.mkdir(parents=True, exist_ok=True)
    
    # 禁用pytest-html的默认报告
    try:
        pytest_html = pytest.importorskip("pytest_html")
        pytest_html.HTMLReport = object  # 禁用内置HTML报告
    except ImportError:
        pass
    
    # 使用自定义报告
    custom_reporter = TestReporter(output_dir=REPORTS_DIR)
    yield custom_reporter
    
    # 测试结束后生成报告
    report_paths = custom_reporter.generate_report()
    # print(f"\n自定义报告已生成：\nHTML: {report_paths['html']}")
    # print(f"\n生成的报告路径：\nHTML: {report_paths['html']}\nCSV: {report_paths['csv']}")

@pytest.fixture(scope="class")
def driver_init(request):
    # 使用绝对路径
    chrome_driver_path = PROJECT_ROOT / "driver" / "chromedriver-win64" / "134.0.6998.165" / "chromedriver.exe"
    # chrome_driver_path = Path(__file__).parent.parent / "driver" / "chromedriver-win64" / "134.0.6998.165" / "chromedriver.exe"
    
    if not chrome_driver_path.exists():
        raise FileNotFoundError(f"ChromeDriver not found at: {chrome_driver_path}")

    options = webdriver.ChromeOptions()
    
    options.add_argument("--start-maximized")
    options.add_argument("--disable-gpu")
    options.add_argument("--no-sandbox")
    
    service = Service(executable_path=chrome_driver_path)
    try:
        driver = webdriver.Chrome(service=service, options=options)
        request.cls.driver = driver
        yield driver
    finally:
        driver.quit()
    